import { AfterViewChecked, Component, Injector, ViewChild, OnInit } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { UserServiceProxy, WorkflowServiceProxy, ProcessingContentApplyChangeMainDto, ProcessingContentApplyChangeStepUserDto, ProcessingContentApplyChangeDetailDto, ProcessingContentApplyChangeServiceServiceProxy, ProcessingContentApplyChangeInputDto } from '@shared/service-proxies/service-proxies';

import { SelectItem, SelectItemGroup } from 'primeng/api';

@Component({
    selector: 'CrucialProcessingContentApplyChangeCreate',
    templateUrl: './CrucialProcessingContentApplyChangeCreate.component.html',
    styleUrls: ['./CrucialProcessingContentApplyChangeCreate.component.css']
})
export class CrucialProcessingContentApplyChangeCreateComponent extends AppComponentBase implements OnInit {
    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('teskdataTable') teskdataTable: Table;
    // @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;
    filterText = '';
    selectedCar3: string;
    detailsprimengTableHelper: PrimengTableHelper;
    _processingContentApplyChangeDetailsDto: ProcessingContentApplyChangeDetailDto[];
    clonedOutsourcings: { [s: number]: ProcessingContentApplyChangeDetailDto; } = {};
    _processingContentApplyChangeMainDto: ProcessingContentApplyChangeMainDto = new ProcessingContentApplyChangeMainDto();
    stepusers: ProcessingContentApplyChangeStepUserDto;
    users: SelectItem[];

    SupplierAyy: SelectItem[];

    selectProcessingContentApplyChangeDetailDto: ProcessingContentApplyChangeDetailDto[];
    index = 0;
    constructor(injector: Injector,
        private _processingContentApplyChangeService: ProcessingContentApplyChangeServiceServiceProxy,
        private _userService: UserServiceProxy,
        private _workflowService: WorkflowServiceProxy
    ) {
        super(injector);
        this.detailsprimengTableHelper = new PrimengTableHelper();
        this.stepusers = new ProcessingContentApplyChangeStepUserDto();
    }

    ngOnInit(): void {


    }

    show(): void {
        this.selectProcessingContentApplyChangeDetailDto = new Array<ProcessingContentApplyChangeDetailDto>();
        this._userService.getAllUserForDropDown2().subscribe(resultdata => {
            console.log(resultdata);
            this.users = resultdata;
        });
        this.active = true;
        this.modal.show();
    }
    close(): void {
        this.active = false;
        this.modal.hide();
    }
    onShown(): void {

    }
    getTasks(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this.primengTableHelper.showLoadingIndicator();
        this._processingContentApplyChangeService.getProcessingContentFormChangeModelByCode(
            1,
            this.filterText,
            'Code',
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                console.log(result);
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    //依据申请单获取任务
    SelectTask(record) {
        console.log(record);
        this._processingContentApplyChangeMainDto.applyUnit = record.applyUnit;
        let _supplier = record.supplierUnit.split(',');
        this.SupplierAyy = new Array();
        this.SupplierAyy.push({ label: '请选择供方', value: '请选择供方' });
        _.forEach(_supplier, viewItem => {
            console.log(viewItem);
            this.SupplierAyy.push({ label: viewItem, value: viewItem });
        });
        this._processingContentApplyChangeMainDto.supplierUnit = this.SupplierAyy[0].value;

        this._processingContentApplyChangeMainDto.code = record.code;
        this._processingContentApplyChangeService.getProcessingContentApplyChangeDetailByWorkFlowId(record.workflowId).subscribe(dto => {
            console.log(dto);
            this._processingContentApplyChangeDetailsDto = dto;
        });

        this._processingContentApplyChangeService.buildProcessingContentApplyChangeOrderCodeByOutsourcingCode(record.code).subscribe(code => {
            this._processingContentApplyChangeMainDto.changedCode = code;
        });
        this.index = 1;
    }
    supplierChange(evt): void {

        console.log(evt.value);

        let newList = new Array();
        console.log(this._processingContentApplyChangeDetailsDto);
        _.forEach(this._processingContentApplyChangeDetailsDto, viewItem => {
            console.log(viewItem.supplierName);
            if (viewItem.supplierName === evt.value) {
                newList.push(viewItem);
            }
        });
        console.log(newList);
        this.detailsprimengTableHelper.totalRecordsCount = newList.length;
        this.detailsprimengTableHelper.records = newList;
        this.detailsprimengTableHelper.hideLoadingIndicator();

    }

    handleChange(e) {
        this.index = e.index;
    }


    onRowEditInit(quotationmodel: ProcessingContentApplyChangeDetailDto) {
        console.log(quotationmodel);
        this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
    }

    onRowEditSave(quotationmodel: ProcessingContentApplyChangeDetailDto) {
        console.log(quotationmodel);
        if (!quotationmodel.workStatus) {
            this.notify.info('请填写原加工状态');
            return false;
        }
        if (!quotationmodel.changedWorkStatus) {
            this.notify.info('请填写变更后加工状态');
            return false;
        }
        if (!quotationmodel.changeRemark) {
            this.notify.info('请填写变更原因');
            return false;
        }
        if (!quotationmodel.currentOutsourcingProgress) {
            this.notify.info('请填写当前外包产品进度');
            return false;
        }
        if (!quotationmodel.deliveryRate) {
            this.notify.info('请填写交付进度');
            return false;
        }
        if (quotationmodel.unitPrice <= 0) {
            this.notify.info('变更后参考单价必须大于0');
            return false;
        }
        delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
        let _current = this._processingContentApplyChangeDetailsDto.find((element) => (element.taskForModelId == quotationmodel.taskForModelId));
        if (_current === undefined) {
            quotationmodel.workStatus = quotationmodel.workStatus;
            quotationmodel.changedWorkStatus = quotationmodel.changedWorkStatus;
            quotationmodel.changeRemark = quotationmodel.changeRemark;
            quotationmodel.currentOutsourcingProgress = quotationmodel.currentOutsourcingProgress;
            quotationmodel.deliveryRate = quotationmodel.deliveryRate;
            quotationmodel.unitPrice = quotationmodel.unitPrice;
            quotationmodel.sumPrice = quotationmodel.unitPrice * quotationmodel.outsourcingAmount;
            this.selectProcessingContentApplyChangeDetailDto.push(quotationmodel);
        } else {
            _current.workStatus = quotationmodel.workStatus;
            _current.changedWorkStatus = quotationmodel.changedWorkStatus;
            _current.changeRemark = quotationmodel.changeRemark;
            _current.currentOutsourcingProgress = quotationmodel.currentOutsourcingProgress;
            _current.deliveryRate = quotationmodel.deliveryRate;
            _current.unitPrice = quotationmodel.unitPrice;
            _current.sumPrice = quotationmodel.unitPrice * quotationmodel.outsourcingAmount;
            this.selectProcessingContentApplyChangeDetailDto.push(_current);
        }
    }

    onRowEditCancel(quotationmodel: ProcessingContentApplyChangeDetailDto, index: number) {
        console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
        this._processingContentApplyChangeDetailsDto[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
        delete this._processingContentApplyChangeDetailsDto[quotationmodel.taskForModelId];
    }

    save() {
        let input = new ProcessingContentApplyChangeInputDto();
        // tslint:disable-next-line: triple-equals

        input.workflowName = '关键过程外包加工内容变更通知单';
        console.log(this.selectProcessingContentApplyChangeDetailDto);
        if (this.selectProcessingContentApplyChangeDetailDto.length === 0) {
            this.notify.info('请填写变更内容');
            this.saving = false;
            return;
        }

        //判断审批用户是否设置
        if (!this.stepusers.workshopManager||this.stepusers.workshopManager==='-1') {
            this.notify.info('请选择申请单位经办人');
            this.saving = false;
            return;
        }
        if (!this.stepusers.workShopLeader||this.stepusers.workShopLeader==='-1') {
            this.notify.info('请选择申请单位主管领导');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionModelManager||this.stepusers.plannedProductionModelManager==='-1') {
            this.notify.info('请选择计划生产处型号主管');
            this.saving = false;
            return;
        }
        if (!this.stepusers.plannedProductionDirector||this.stepusers.plannedProductionDirector==='-1') {
            this.notify.info('请选择计划生产处主管处长');
            this.saving = false;
            return;
        }

        input.stepUserDto = this.stepusers;
        input.processingContentApplyChangeMainDto = this._processingContentApplyChangeMainDto;
        input.processingContentApplyChangeDetailDtos = this.selectProcessingContentApplyChangeDetailDto;
        this.saving = true;

        console.log(input);

        this._processingContentApplyChangeService.createOrUpdateCrucialProcessingContentApplyChange(input)
            .pipe(finalize(() => { this.saving = false; }))
            .subscribe(() => {
                this.close();
            });
    }

}
